 /**
 * DISCLIMER: 
 * this library is an opensource, feel free to edit or redistribute it
 * but use it with you own risk
 * 
 * ktutnik
 */
package org.ticlib.navigator
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import mx.events.BrowserChangeEvent;
	import mx.managers.IBrowserManager;
	
	public class AirBrowserManager extends EventDispatcher implements IBrowserManager
	{
		protected var prevHistories:Array;
		protected var nextHistories:Array;
		
		private var currentFragment:String;
		private var currentTitle:String;
		
		[Bindable] public var isPreviousButtonEnable:Boolean;
		[Bindable] public var isNextButtonEnable:Boolean;
		
		public function AirBrowserManager(target:IEventDispatcher=null)
		{
			//super(target);
		}
		
		private function updateButtonState():void
		{
			isPreviousButtonEnable = (prevHistories.length > 0);
			isNextButtonEnable = (nextHistories.length > 0);
		}
		
		public function clear():void
		{
			init();
			updateButtonState();
		}
		
		public function next():void
		{
			if(nextHistories.length == 0) return;
			prevHistories.push(currentFragment);
			currentFragment = nextHistories.pop() as String;
			updateButtonState();
			dispatchEvent(new Event("fragmentChange"));
			
			var ev:BrowserChangeEvent = new BrowserChangeEvent(BrowserChangeEvent.BROWSER_URL_CHANGE, true);
			dispatchEvent(ev);
		}
		
		public function previous():void
		{
			if(prevHistories.length == 0) return;
			nextHistories.push(currentFragment);
			currentFragment = prevHistories.pop() as String;
			updateButtonState();
			dispatchEvent(new Event("fragmentChange"));
			
			var ev:BrowserChangeEvent = new BrowserChangeEvent(BrowserChangeEvent.BROWSER_URL_CHANGE, true);
			dispatchEvent(ev);
		}
		
		public function get base():String
		{
			return null;
		}
		
		[Bindable("fragmentChange")]
		public function get fragment():String
		{
			return currentFragment;
		}
		
		[Bindable("fragmentChange")]
		public function get title():String
		{
			return currentTitle;
		}
		
		[Bindable("fragmentChange")]
		public function get url():String
		{
			return currentFragment;
		}
		
		public function setFragment(value:String):void
		{
			if((currentFragment != null) && (currentFragment != value))
			{
				prevHistories.push(currentFragment);
				nextHistories = new Array();
				updateButtonState();
			}
			currentFragment = value;
			dispatchEvent(new Event("fragmentChange"));
		}
		
		public function setTitle(value:String):void
		{
			currentTitle = value;
			dispatchEvent(new Event("fragmentChange"));
		}
		
		public function init(value:String="", title:String=""):void
		{
			if(value != "") setFragment(value);
			if(title != "") currentTitle = title;
			prevHistories = new Array();
			nextHistories = new Array();
			
			isPreviousButtonEnable = false;
			isNextButtonEnable = false;
		}
		
		public function initForHistoryManager():void
		{
		}
	}
}